import { defineStore } from 'pinia'
import { ref, onMounted } from 'vue'
import { useMembersStore } from './members'
import { useMemberCardStore } from './memberCard'
import { useConsumptionRecordStore } from './consumptionRecord'
import { useOperationRecordStore } from './operationRecord'
import { ElMessage, ElMessageBox } from 'element-plus'
import { storeToRefs } from 'pinia'

export const useMemberCardRelationStore = defineStore('memberCardRelation',() => {
    const membersStore = useMembersStore()
    const memberCardStore = useMemberCardStore()
    const consumptionRecordStore = useConsumptionRecordStore()
    const {consumptionRecords} = storeToRefs(consumptionRecordStore)
    const operationRecordStore = useOperationRecordStore()

    const memberCardRelations = ref([
        {
            memberId: 1,
            memberCardId: 1,
            memberCardName: '',
            type: '',
            availableTimes: 10,
            expirationDate: "2025-01-01",
            isAvailable: true,
        }
    ])

    const addMemberCardRelation = (memberCardRelation) => {
        const member = membersStore.getMemberById(memberCardRelation.memberId)
        const memberCard = memberCardStore.getMemberCardById(memberCardRelation.memberCardId)
        if (member.memberCards.includes(memberCard.memberCardName)){
            ElMessage.warning(`${member.memberName}会员已绑定过${memberCard.memberCardName}`)
            return;
        }
        memberCard.num += 1
        memberCardRelations.value.push({
            memberId: memberCardRelation.memberId,
            memberCardId: memberCardRelation.memberCardId,
            memberCardName: memberCard.memberCardName,
            type: memberCard.type,
            availableTimes: memberCard.availableTimes + memberCardRelation.rechargeTimes,
            expirationDate: calcExpirationDate(new Date(), memberCard.availableDays),
            isAvailable: true
        })
        member.memberCards.push(memberCard.memberCardName)
        consumptionRecordStore.addRecord({
            memberId: memberCardRelation.memberId,
            memberCardId: memberCardRelation.memberCardId,
            consumeTimes: 0,
            remainingTimes: memberCard.availableTimes + memberCardRelation.rechargeTimes,
            consumeAmount: memberCardRelation.receivedAmount,
            operationType: '绑卡操作',
            operator: '张老师',
            remark: memberCardRelation.remark
        })
        operationRecordStore.addRecord({
            memberId: memberCardRelation.memberId,
            memberCardId: memberCardRelation.memberCardId,
            operationType: '绑卡操作',
            changeTimes: 0,
            changeMoney: -memberCardRelation.receivedAmount,
            operator: '张老师',
            remark: memberCardRelation.remark,
            status: '已激活'
        })
        ElMessage.success('绑定成功')
    }

    const calcExpirationDate = (startDay, avaliableDays) =>{
        const date = new Date(startDay.getTime() + avaliableDays * 24 * 60 * 60 * 1000)
        const year = date.getFullYear();
        const month = date.getMonth() + 1;
        const day = date.getDate();
        return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
    }

    const parseDate = (str) =>{
        const parts = str.split('-');
        const day = parseInt(parts[2], 10);
        const month = parseInt(parts[1], 10) - 1; // 月份是从0开始的
        const year = parseInt(parts[0], 10);
        return new Date(year, month, day);
    }

    const recharge = (memberId, memberCardId, rechargeForm)=> {
        const relation = memberCardRelations.value.find(card => card.memberId === memberId && card.memberCardId === memberCardId)
        if(relation){
            relation.availableTimes += rechargeForm.rechargeTimes
            relation.expirationDate = calcExpirationDate(parseDate(relation.expirationDate), rechargeForm.prolongDays)
            operationRecordStore.addRecord({
                memberId: memberId,
                memberCardId: memberCardId,
                operationType: '充值操作',
                changeTimes: rechargeForm.rechargeTimes,
                changeMoney: rechargeForm.receivedAmount,
                operator: '张老师',
                remark: rechargeForm.remark,
                status: '已激活'
            })
            ElMessageBox.alert('充值成功', {
                type: 'success'
            });
        }
    }

    const consume = (memberId, memberCardId, consumeForm)=> {
        const relation = memberCardRelations.value.find(card => card.memberId === memberId && card.memberCardId === memberCardId)
        if(relation){
            if (relation.availableTimes >= consumeForm.consumeTimes){
                relation.availableTimes -= consumeForm.consumeTimes
                consumptionRecordStore.addRecord({
                    memberId: relation.memberId,
                    memberCardId: relation.memberCardId,
                    consumeTimes: consumeForm.consumeTimes,
                    remainingTimes: relation.availableTimes,
                    consumeAmount: consumeForm.consumeAmount,
                    operationType: '会员上课扣费操作',
                    operator: '张老师',
                    remark: consumeForm.remark
                })
                operationRecordStore.addRecord({
                    memberId: memberId,
                    memberCardId: memberCardId,
                    operationType: '会员上课扣费操作',
                    changeTimes: -consumeForm.consumeTimes,
                    changeMoney: -consumeForm.consumeAmount,
                    operator: '张老师',
                    remark: consumeForm.remark,
                    status: '已激活'
                })
                ElMessageBox.alert('扣费成功', {
                    type: 'success'
                });
            }
            else{
                ElMessageBox.alert('扣费失败，可用次数不足', {
                    type: 'error'
                })
            }
        }
    }

    const setAvailable = (memberId, memberCardId, available) =>{
        const card = memberCardRelations.value.find(card => card.memberId === memberId && card.memberCardId === memberCardId)
        if(card){
            card.isAvailable = available
            operationRecordStore.addRecord({
                memberId: memberId,
                memberCardId: memberCardId,
                operationType: available ? '激活会员卡操作' : '停用会员卡操作',
                changeTimes: 0,
                changeMoney: 0,
                operator: '张老师',
                remark: '',
                status: available ? '已激活' : '已停用'
            })
        }
    }

    const setMemberCardToMembers = () => {
        memberCardRelations.value.forEach(card => {
            const member = membersStore.getMemberById(card.memberId)
            const memberCard = memberCardStore.getMemberCardById(card.memberCardId)
            if (member && memberCard) {
                member.memberCards.push(memberCard.memberCardName)
            }
        })
    }

    const setMemberCardNameToRelation = () =>{
        memberCardRelations.value.forEach(card => {
            const memberCard = memberCardStore.getMemberCardById(card.memberCardId)
            if (memberCard) {
                card.memberCardName = memberCard.memberCardName
                card.type = memberCard.type
            }
        })
    }

    const setMemberCardNameToRecords = () =>{
        consumptionRecords.value.forEach((record) => {
            const memberCard = memberCardStore.getMemberCardById(record.memberCardId)
            record.memberCardName = memberCard.memberCardName
        })
    }

    const getMemberCardsByMemberId = (memberId) => {
        return memberCardRelations.value.filter(card => card.memberId === memberId)
    }

    onMounted(() => {
        setMemberCardToMembers()
        setMemberCardNameToRelation()
        setMemberCardNameToRecords()
    })

    return {
        memberCardRelations,
        setAvailable,
        addMemberCardRelation,
        getMemberCardsByMemberId,
        recharge,
        consume,
    }
})
